package com.cavy.platform.server.repository.impl;

import com.cavy.platform.server.BeansProvider;
import com.cavy.platform.server.CavyConfig;
import com.cavy.platform.server.domain.Plugin;
import com.cavy.platform.server.domain.PluginRepositorySetting;
import com.cavy.platform.server.repository.PluginRepository;
import com.cavy.platform.server.util.FileUtils;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import static com.cavy.platform.server.domain.PluginRepositorySetting.LOCAL_REPOSITORY_CODE;
import static com.cavy.platform.server.repository.impl.PluginRepositoryImpl.DESCRIPTION_FILE_NAME;
import static com.cavy.platform.server.repository.impl.PluginRepositoryImpl.OBJECT_FILE_NAME;

/**
 * 插件文件存储
 */
public class LocalPluginRepositoryImpl extends RemotePluginRepositoryImpl implements PluginRepository {

    public LocalPluginRepositoryImpl(String dir, PluginRepositorySetting setting) {
        super(dir, setting);
    }

    public static PluginRepositorySetting getLocalSetting() {
        CavyConfig bean = BeansProvider.getBean(CavyConfig.class);
        assert bean != null;
        String s = bean.getPlugin().getDir() + LOCAL_REPOSITORY_CODE;
        return new PluginRepositorySetting().setCode(LOCAL_REPOSITORY_CODE).setName("本地仓库")
                .setBranchName("").setUrl(s);
    }

    @Override
    public void create(Plugin plugin) throws IOException {
        File pluginDir = getPluginDir(plugin.getName(), plugin.getVersion());
        boolean mkdirs = pluginDir.mkdirs();
        if (!mkdirs) {
            throw new RuntimeException("无法创建插件目录," + pluginDir.getPath());
        }
        saveDescription(pluginDir, plugin.getDescription());
        saveInfoJson(pluginDir, plugin);
    }

    @Override
    public void delete(String name, String version) {
        File pluginDir = getPluginDir(name, version);
        FileUtils.delFolder(pluginDir.getPath());
        File parentFile = pluginDir.getParentFile();
        String[] list = parentFile.list();
        if (list != null && list.length == 0) {
            FileUtils.delFolder(parentFile.getPath());
        }
    }

    //保存插件的json
    private void saveInfoJson(File pluginDir, Plugin plugin) throws IOException {
        File file = new File(pluginDir, OBJECT_FILE_NAME);
        ObjectMapper mapper = new ObjectMapper();
        mapper.writeValue(file, plugin);
    }

    //保存插件的描述文件
    private void saveDescription(File pluginDir, String description) throws IOException {
        File desc = new File(pluginDir, DESCRIPTION_FILE_NAME);
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(desc))) {
            writer.write(description);
        }
    }

    @Override
    public void refresh() {
        //不做任何实现
    }
}
